package com.netx.ut.lib.hibernate;


public class Validator {

	public static void validateAlphaText(String s) throws ValidationException {
		_validateText(s, false, "- \'");
	}

	public static void validateReadableText(String s) throws ValidationException {
		_validateText(s, true, "- \'");
	}

	public static void validateCodeIdentifier(String username) throws ValidationException {
		_validateIdentifier(username, "._$");
	}

	public static void validateTextIdentifier(String username) throws ValidationException {
		_validateIdentifier(username, "-_");
	}

	public static void validateUsername(String username) throws ValidationException {
		_validateIdentifier(username, ".-_");
	}

	private static void _validateText(String s, boolean allowDigits, String allowedChars) throws ValidationException {
		String illegal = _checkString(s, allowDigits, allowedChars);
		if(illegal != null) {
			try {
				new Integer(illegal);
			}
			catch(NumberFormatException nfe) {
				throw new ValidationException("illegal characters found: "+illegal);
			}
			throw new ValidationException("no digits allowed");
		}
	}

	private static void _validateIdentifier(String s, String allowedChars) throws ValidationException {
		if(!Character.isLetter(s.charAt(0))) {
			throw new ValidationException("the first character must be a letter");
		}
		String illegal = _checkString(s, true, allowedChars);
		if(illegal != null) {
			throw new ValidationException("illegal characters found: "+illegal);
		}
	}

	private static String _checkString(String s, boolean allowDigits, String allowedChars) {
		StringBuilder sb = new StringBuilder();
		for(int i=0; i<s.length(); i++) {
			char c = s.charAt(i);
			if(Character.isLetter(c)) {
				continue;
			}
			if(allowDigits) {
				if(Character.isDigit(c)) {
					continue;
				}
			}
			if(allowedChars.indexOf(c) != -1) {
				continue;
			}
			else {
				if(Character.isWhitespace(c)) {
					sb.append("<space>");
				}
				else {
					sb.append(c);
				}
			}
		}
		if(sb.length() > 0) {
			return sb.toString();
		}
		return null;
	}
}
